package com.application.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.util.Optional;

/**
 * 获取openid的工具类
 * @since  2023-1-16
 * @author  hyj
 * @version 1.0
 */
@Slf4j
@Component
public class HttpUtil {
    /**
     * 通过code获取信息
     * @param code
     * @return
     */
    private  static  String appid="wx1a2e690603ee4608";

    private static String secret="7bab890844da1452093d683e5327364f";

    private final static String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取openid
     * @param code
     * @return
     */
    public  String getOpenid(String code){
        String url = WX_LOGIN_URL + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = restTemplate.getForObject(url, JSONObject.class);
        Optional<JSONObject> optionalJSONObject = Optional.ofNullable(jsonObject);
        System.out.println(optionalJSONObject);
        if(!optionalJSONObject.isPresent()){
            //获取openid失败
            return null;
        }
        var data = jsonObject.getInnerMap();
        System.out.println(data);
        //assert data.get("openid") != null;
        String openid= (String) data.get("openid");
        System.out.println("op" + openid);
        return openid;
    }
}


